package cn.edu.bupt.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 记录日志类
 * 通过aspect
 */
@Aspect // 标记这是一个切面类
/**
 *  泛指各种组件，就是说当我们的类不属于各种归类的时候（不属于@Controller、@Services等的时候），
 *  我们就可以使用@Component来标注这个类
 */
@Component
public class LogAspect {
    // 用于控制台日志输出
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 定义切点，用于扫描：cn.edu.bupt.blog.web 的所有类的所有方法
    @Pointcut("execution(* cn.edu.bupt.blog.web.*.*(..))")
    public void log() {
    }

    // 界面点之前执行
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        // 获取HttpServletRequest
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();;
        // 参数列表
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
        logger.info("request ---- {}",requestLog);
    }

    // 界面点之后执行
    @After("log()")
    public void doAfter() {
        logger.info("----------doAfter----------");
    }

    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturning(Object result) {
        logger.info("Return ------ {}",result );
    }

    // 请求日志对象
    private class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        // 参数列表
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
